package sdu.ltp.entity;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 数据库连接池
 * @author ljh_2015
 *
 */
public class DataBasePool {

    private int max_num = 20;
    //等待队列
    private BlockingQueue<Connection> wait_connection = new LinkedBlockingQueue<>(max_num);
    private final static int TIMEOUT = 1000*60*60;

    public DataBasePool() {
	init();
	Timer timer = new Timer();
	timer.schedule(new RefreshTask(), 0,TIMEOUT);
    }

    public DataBasePool(int max_num) {
	init(max_num);
    }

    public void init() {
	init(max_num);
    }

    /**
     * 初始化
     * @throws InterruptedException 
     */
    public void init(int max_num) {
	for(int i=0;i<max_num;i++) {
	    try {
		wait_connection.put(DataBaseConnection.getConnection());
	    } catch (InterruptedException e) {
		continue;
	    }
	}
    }

    /**
     * 创建连接
     * @throws InterruptedException 
     */
    public Connection createConnection() {
	Connection conn = wait_connection.poll();
	if(!DataBaseConnection.isUnException(conn)) {
	    conn = DataBaseConnection.getConnection();
	}
	return conn;
    }

    /**
     * 关闭连接
     * @param conn
     */
    public void closeConnection(Connection conn) {
	try {
	    wait_connection.put(conn);
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    }

    /**
     * 刷新连接
     * @throws InterruptedException 
     */
    public synchronized void refreshConnections() throws InterruptedException {
	if(wait_connection==null) {
	    System.out.println("连接池不存在无法刷新");
	    return;
	}
	Connection conn = null;
	int size = wait_connection.remainingCapacity();
	while((conn = wait_connection.poll(10, TimeUnit.MILLISECONDS))!=null) {
	    try {
		if(!conn.isClosed()) {
		    conn.close();
		}
	    } catch (SQLException e) {
		continue;
	    }
	}
	System.out.println("重新创建"+size+"个连接放入缓冲池");
	init(size);
    }

    public class RefreshTask extends TimerTask {

	@Override
	public void run() {
	    try {
		//执行刷新
		synchronized (wait_connection) {
		    refreshConnections();
		}
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}

    }
}
